//
// Created by baigui on 2021/10/18.
//

#ifndef SIMPLE_PLAYER_TS_DEMUX_H
#define SIMPLE_PLAYER_TS_DEMUX_H

#include "Demux.h"
#include "MediaPlayer.h"
#include <mediaStream.h>
#include <ts/TsFilter.h>
#include "FileDatasource.h"
#include "ts/ts_pid.h"

#define TS_PACKET_SIZE_188 188
#define TS_PACKET_SIZE_192 192
#define TS_PACKET_SIZE_204 204
#define TS_PACKET_SIZE_MAX 204
#define TS_HEADER_SIZE 4


class TsDemux : public Demux, public SectionFilterCallBack {
public:

    TsDemux(weak_ptr<MediaPlayer> player);

    ~TsDemux();

    bool Open(void *path) override;

    bool start() override;

    void handle(int , void *) override ;

    void requestbuffer() override;

    void OnPatCallBack(int pmtPid,int id) override;
    void OnPmtCallBack(int pmtPid,MediaStream *stream) override;

private:

    int DetectPacketSize();

    MediaStream *mMediaStream;
    FILE        *fp = nullptr;

    int          i_packet_size;
    //对于蓝光电影，前面有4位
    unsigned     i_packet_header_size = 0;

    BaseStream *mFileDatasource;


    int handle_packet(const uint8_t *packet);

    int discard_pid(int pid);

    TsBaseFilter *pids[8192];
    int current_pid;
    int scan_all_pmts;
    int nb_prg;
    int64_t raw_packet_size;

    int handle_packets(int64_t nb_packets);

    int read_packet(uint8_t packet[], int64_t size);

    int mpegts_open_section_filter(int pid, MpegTSFilterType type, int check_crc);
};


#endif //SIMPLE_PLAYER_MP4DEMUX_H
